package com.iasku.iaskueleclass_phone.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.kobjects.base64.Base64;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import com.iasku.constant.Constant;
import com.iasku.constant.IntentConfig;
import com.iasku.entity.IaskuQuestion;
import com.iasku.entity.Point;
import com.iasku.entity.Rectangle;
import com.iasku.iaskueleclass_phone.R;
import com.iasku.iaskueleclass_phone.ReturnData;
import com.iasku.iaskueleclass_phone.Status;
import com.iasku.manager.DataManager;
import com.iasku.manager.IDataManager;
import com.iasku.util.BaseUtil;

/**
 * 错题本正在订正，未解答
 */
public class ErrorBookQuestionSubmitAnswerActivity extends BaseActivity {
    private static final int TASK_SUBMIT_HANDIMG = 1;
    private static final int TASK_START_SYSTEMRECOMMEND = 2;
    private static final int TASK_GET_IMGPIC = 3;

    private LinearLayout btnTools, btnSubmit;
    private ImageButton btnPrevPage, btnNextPage;
    private ImageView imgv;

    private LinearLayout layoutBottom;
    private String eid;
    private int pageno;
    private int pencolor, g_penWidth = 2, scale = 1, sscale = 0, lheight = 0;
    private int c_purple;
    private List<Point> points = new ArrayList<Point>();
    private List<Point> apoint = new ArrayList<Point>();
    private ArrayList<Rectangle> rects = new ArrayList<Rectangle>();
    private int pic_w,pic_h;
    private float pic_w_scale_read;
    private float pic_h_scale_read;
    private String appdir;
    private Bitmap[] picimg, bgnimg;
    private Bitmap bgnimg0, bgnimg1;
    private Bitmap tmpimg;
    private int goedit = 0, startx = 0, starty = 0, penstyle;
    private int screenWidth;
    private int rect_xy = 10, rect_w = 20;
    private PopupWindow popTools;
    private ImageView b_pen, b_line, b_eraser, b_circle, b_oval, b_arrow, b_rect;
    private ImageView b_black, b_blue, b_purple;
    private static final int STATUS_PEN = 0;
    private static final int STATUS_LINE = 1;
    private static final int STATUS_ARROW = 2;
    private static final int STATUS_OVAL = 3;
    private static final int STATUS_CIRCLE = 4;
    private static final int STATUS_RECT = 5;
    private static final int STATUS_ERASER = 6;
    private IaskuQuestion iQuestion;
    private int[] isedit;
    private int piccount = 1;
    private String[] mCommandArr;
    private String mAnswerid;
    private Bitmap mCurBitmap;
    private int subjectid;
    private int g_penDash = 0;

    private void setupView() {
        btnTools = (LinearLayout) findViewById(R.id.btn_answer_doing_tools);
        btnSubmit = (LinearLayout) findViewById(R.id.btn_answer_doing_submit);
        btnPrevPage = (ImageButton) findViewById(R.id.iv_answer_previous);
        btnNextPage = (ImageButton) findViewById(R.id.iv_answer_next);
        imgv = (ImageView) findViewById(R.id.iv_answer_img);
        layoutBottom = (LinearLayout) findViewById(R.id.layout_answer_bottom);
    }

    /** 初始化工具栏 */
    private void initPopTools() {
        View view = LayoutInflater.from(this).inflate(R.layout.homework_answer_tools, null);
        popTools = new PopupWindow(view);
        b_pen = (ImageView) view.findViewById(R.id.b_pen);
        b_line = (ImageView) view.findViewById(R.id.b_line);
        b_rect = (ImageView) view.findViewById(R.id.b_rect);
        b_arrow = (ImageView) view.findViewById(R.id.b_arrow);
        b_eraser = (ImageView) view.findViewById(R.id.b_eraser);
        b_circle = (ImageView) view.findViewById(R.id.b_circle);
        b_oval = (ImageView) view.findViewById(R.id.b_oval);
        b_black = (ImageView) view.findViewById(R.id.b_black);
        b_blue = (ImageView) view.findViewById(R.id.b_blue);
        b_purple = (ImageView) view.findViewById(R.id.b_purple);
        Drawable cur_draw = getResources().getDrawable(R.drawable.correcting_selected);
        b_pen.setImageDrawable(cur_draw);
        b_black.setImageDrawable(cur_draw);
    }

    private void addListener() {
        MyOnClickListener mListener = new MyOnClickListener();
        btnTools.setOnClickListener(mListener);
        btnSubmit.setOnClickListener(mListener);
        btnPrevPage.setOnClickListener(mListener);
        btnNextPage.setOnClickListener(mListener);
        mBarRightBtn.setOnClickListener(mListener);

        b_pen.setOnClickListener(mListener);
        b_line.setOnClickListener(mListener);
        b_eraser.setOnClickListener(mListener);
        b_circle.setOnClickListener(mListener);
        b_oval.setOnClickListener(mListener);
        b_arrow.setOnClickListener(mListener);
        b_rect.setOnClickListener(mListener);
        b_black.setOnClickListener(mListener);
        b_blue.setOnClickListener(mListener);
        b_purple.setOnClickListener(mListener);

    }

    private void initView() {
        mBarRightBtn.setVisibility(View.VISIBLE);
        setupView();
        picimg = new Bitmap[10];
        bgnimg = new Bitmap[10];
        isedit = new int[10];
        iQuestion = getIntent().getParcelableExtra(IntentConfig.IQUESTION_INFO);
        eid = getIntent().getStringExtra(IntentConfig.EXAMID);
        subjectid = getIntent().getIntExtra(IntentConfig.SUBJECT_ID, 0);
        appdir = getApplicationContext().getFilesDir().getAbsolutePath();
        String attach = getIntent().getStringExtra(IntentConfig.ANSWER_ATTACH);
        try {
            JSONArray mJSONArray = new JSONArray(attach);
            piccount = mJSONArray.length();
            mCommandArr = new String[piccount];
            picimg = new Bitmap[piccount];
            bgnimg = new Bitmap[piccount];
            mAnswerid = mJSONArray.getJSONObject(0).optString("answerid");
            for (int i = 0; i < mJSONArray.length(); i++) {
                JSONObject attachJSON = mJSONArray.getJSONObject(i);
                mCommandArr[i] = attachJSON.optString("cmdtext");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        pencolor = Color.BLACK;
        c_purple = getResources().getColor(R.color.purple);
        setButtonStatus();
        picdraw();
        initPopTools();
        addListener();
        mBarCenterTitleTv.setText("第" + (pageno + 1) + "页，共" + piccount + "页");
        startTask(TASK_GET_IMGPIC);
    }
    
    private void setButtonStatus(){
        btnPrevPage.setVisibility(View.VISIBLE);
        btnNextPage.setVisibility(View.VISIBLE);
        if (picimg.length == 1) {
            btnPrevPage.setVisibility(View.GONE);
            btnNextPage.setVisibility(View.GONE);
        } else {
            if (pageno == 0) {
                btnPrevPage.setVisibility(View.GONE);
            } else if (pageno == picimg.length - 1) {
                btnNextPage.setVisibility(View.GONE);
            }
        }
    }

    private void getLocalJpg() {
        File file = new File(appdir + "/" + Constant.USER_IASKUNAME + "/" + eid + "/" + iQuestion.getQuestionno()
                                + "/" + iQuestion.getSubmitTimes());
        File[] files = file.listFiles();
        if (files != null) { // 判断是否为空，不判断会出异常
            for (int i = 0; i < files.length; i++) { // 逐个扫描
                if (files[i].isFile()) { // 判断如果是个文件
                    if ((files[i].getName().endsWith(".jpg")) && (files[i].getName().startsWith(iQuestion.getQuestionno() + "_"))) { // 判断文件是否以.mp3结尾，是则绝对路径存入MP3文件路径数组
                        String ss = files[i].getName();
                        ss = ss.substring(ss.indexOf("_") + 1);
                        ss = ss.substring(0, ss.indexOf("."));
                        int ii = Integer.parseInt(ss);
                        FileInputStream fin = null;
                        try {
                            fin = new FileInputStream(files[i]);
                        } catch (FileNotFoundException e) {
                            // TODO Auto-generated catch block
                        }
                        picimg[ii - 1] = BitmapFactory.decodeStream(fin).copy(Bitmap.Config.ARGB_8888, true);

                        try {
                            fin.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        isedit[ii - 1] = 1;
                        if (ii > piccount)
                            piccount = ii;
                    }
                }
            }
        }

        isedit[0] = 1;
    }


    private void picdraw() {
        /** 开始画线 */
        imgv.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                Canvas cv = null;
                Paint p = new Paint();
                p.setColor(pencolor);
                p.setStyle(Paint.Style.STROKE);
                p.setStrokeWidth(g_penWidth);
                p.setAntiAlias(true);
                switch (action) {
                // 当按下的时候
                case (MotionEvent.ACTION_DOWN):
                    tmpimg = Bitmap.createBitmap(picimg[pageno]);
                    startx = (int) event.getX();
                    starty = (int) event.getY();
                    Log.d("xbin", "startx=" + startx + " starty=" + starty);
                    switch (penstyle) {
                    case STATUS_PEN:
                        points.add(new Point(startx / scale, starty / scale - lheight * sscale));
                        apoint.add(new Point(startx / scale, starty / scale - lheight * sscale));
                        break;
                    }
                    break;
                // 当按上的时候
                case (MotionEvent.ACTION_UP):
                    int x2 = (int) event.getX();
                    int y2 = (int) event.getY() - lheight * sscale;
                    switch (penstyle) {
                    case STATUS_PEN:
                        cv = new Canvas(picimg[pageno]);
                        points.add(new Point(x2 / scale, y2 / scale - lheight * sscale));
                        apoint.add(new Point(x2 / scale, y2 / scale - lheight * sscale));
                        for (int i = 1; i < points.size(); i++) {
                            Point pp = points.get(i - 1);
                            Point pp1 = points.get(i);
                            cv.drawLine(pp.getX(), pp.getY(), pp1.getX(), pp1.getY(), p);
                        }
                        points.clear();
                        apoint.clear();
                        cv.save(Canvas.ALL_SAVE_FLAG);
                        break;
                    }
                    if (penstyle != -1) {
                        savejpg();
                    }
                    break;
                // 当触摸的时候
                case (MotionEvent.ACTION_MOVE):
                    switch (penstyle) {
                    case STATUS_PEN:
                        points.add(new Point(event.getX() / scale, event.getY() / scale - lheight * sscale));
                        apoint.add(new Point(event.getX() / scale, event.getY() / scale - lheight * sscale));
                        if (points.size() > 1) {
                            if (cv == null) {
                                cv = new Canvas(picimg[pageno]);
                            }
                            Point pp = points.get(0);
                            Point pp1 = points.get(1);
                            cv.drawLine(pp.getX(), pp.getY(), pp1.getX(), pp1.getY(), p);
                            cv.save(Canvas.ALL_SAVE_FLAG);// 保存
                            points.remove(0);
                        }
                        break;
                    case STATUS_LINE:
                        picimg[pageno] = Bitmap.createBitmap(tmpimg);
                        cv = new Canvas(picimg[pageno]);
                        cv.drawLine(startx / scale, starty / scale - lheight * sscale, event.getX() / scale,
                                event.getY() / scale - lheight * sscale, p);
                        cv.save(Canvas.ALL_SAVE_FLAG);// 保存
                        break;
                    case STATUS_ARROW:
                        picimg[pageno] = Bitmap.createBitmap(tmpimg);
                        cv = new Canvas(picimg[pageno]);
                        drawArrow(cv, p, startx / scale, starty / scale - lheight * sscale, event.getX() / scale,
                                event.getY() / scale - lheight * sscale);
                        cv.save(Canvas.ALL_SAVE_FLAG);// 保存
                        break;
                    case STATUS_OVAL:
                        picimg[pageno] = Bitmap.createBitmap(tmpimg);
                        cv = new Canvas(picimg[pageno]);
                        cv.drawOval(new RectF(startx / scale, starty / scale - lheight * sscale, event.getX() / scale,
                                event.getY() / scale - lheight * sscale), p);
                        cv.save(Canvas.ALL_SAVE_FLAG);// 保存
                        break;
                    case STATUS_CIRCLE:
                        picimg[pageno] = Bitmap.createBitmap(tmpimg);
                        cv = new Canvas(picimg[pageno]);
                        float radius = (float) (Math.sqrt((event.getX() - startx) * (event.getX() - startx)
                                + (starty - event.getY()) * (starty - event.getY())));
                        cv.drawCircle(startx / scale, starty / scale - lheight * sscale, radius / scale, p);
                        cv.save(Canvas.ALL_SAVE_FLAG);// 保存
                        break;
                    case STATUS_RECT:
                        picimg[pageno] = Bitmap.createBitmap(tmpimg);
                        cv = new Canvas(picimg[pageno]);
                        cv.drawRect(new RectF(startx / scale, starty / scale - lheight * sscale, event.getX() / scale,
                                event.getY() / scale - lheight * sscale), p);
                        cv.save(Canvas.ALL_SAVE_FLAG);// 保存
                        break;
                    case STATUS_ERASER:
                        cv = new Canvas(picimg[pageno]);
                        int x = (int) event.getX() >= screenWidth ? screenWidth : (int) event.getX();
                        int y = (int) event.getY() >= pic_h ? pic_h : (int) event.getY();
                        int rect_x = x / scale - rect_xy <= 0 ? 0 : x / scale - rect_xy;
                        int rect_width = rect_x + rect_w >= screenWidth ? (screenWidth - rect_x) : rect_w;
                        int rect_y = y / scale - lheight * sscale - rect_xy <= 0 ? 0 : y / scale - lheight * sscale
                                - rect_xy;
                        int rect_height = rect_y + rect_w >= pic_h ? pic_h - rect_y : rect_w;
                        Bitmap sclone = Bitmap.createBitmap(bgnimg[pageno], rect_x, rect_y, rect_width, rect_height);
                        cv.drawBitmap(sclone, rect_x, rect_y, p);
                        cv.save(Canvas.ALL_SAVE_FLAG);
                        sclone.recycle();
                        Rectangle rect = new Rectangle();
                        rect.setX((x / scale - rect_xy <= 0 ? 0 : x / scale - rect_xy));
                        rect.setY((y / scale - lheight * sscale - rect_xy <= 0 ? 0 : y / scale - lheight * sscale
                                - rect_xy));
                        rect.setWidth(rect_x + rect_w >= screenWidth ? (screenWidth - rect_x) : rect_w);
                        rect.setHeight(rect_y + rect_w >= pic_h ? pic_h - rect_y : rect_w);
                        rects.add(rect);
                        break;
                    }
                    if (penstyle != -1) {
                        isedit[pageno] = 1;
                        goedit = 1;
                    }
                    break;
                }
                imgv.setImageBitmap(picimg[pageno]);
                return true;
            }
        });
    }

    @Override
    protected void onCreate(Bundle saveInstance) {
        // TODO Auto-generated method stub
        super.onCreate(saveInstance);
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        screenWidth = dm.widthPixels;
        setContentView(R.layout.errorbook_answer_doing);
        initTitleBar();
        initView();
    }

    private class MyOnClickListener implements OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.common_titlebar_right_btn_clear:// 清除
                clear();
                break;
            case R.id.btn_answer_doing_tools:// 工具栏
                open_tools();
                break;
            case R.id.btn_answer_doing_submit: // 提交
                submitImg();
                break;
            case R.id.iv_answer_previous:// 上一页
                prev_page();
                break;
            case R.id.iv_answer_next:// 上一页
                next_page();
                break;
            case R.id.b_pen: // 画笔
                pen();
                break;
            case R.id.b_eraser: // 橡皮
                eraser();
                break;
            case R.id.b_rect: // 矩形
                rect();
                break;
            case R.id.b_line: // 直线
                line();
                break;
            case R.id.b_arrow: // 箭头
                arrow();
                break;
            case R.id.b_circle: // 圆
                circle();
                break;
            case R.id.b_oval: // 椭圆
                oval();
                break;
            case R.id.b_blue: // 蓝色
                blue();
                break;
            case R.id.b_black: // 红色
                black();
                break;
            case R.id.b_purple: // 紫色
                purple();
                break;
            }
        }
    }

    private void submitImg() {
        int submitTimes = iQuestion.getSubmitTimes();
        if (submitTimes >= Constant.ERROR_TIMES) {
            BaseUtil.showText(this, "已经订正过，请勿重复订正");
            return;
        }
        iQuestion.setSubmitTimes(submitTimes + 1);
        startTask(TASK_SUBMIT_HANDIMG);
    }

    private void open_tools() {
        if (popTools != null && !popTools.isShowing()) {
            popTools.setWidth(screenWidth - 80);
            popTools.setHeight(layoutBottom.getHeight() * 2);
            popTools.showAsDropDown(layoutBottom, 40, -(popTools.getHeight() + layoutBottom.getHeight() + 2));
        } else {
            popTools.dismiss();
        }
    }

    private void clear() {
        picimg[pageno] = Bitmap.createBitmap(bgnimg0);
        imgv.setImageBitmap(picimg[pageno]);
        String filename = appdir + "/" + Constant.USER_IASKUNAME + "/" + eid + "/" + iQuestion.getQuestionno() + "/"  + 
                             iQuestion.getSubmitTimes()+"/"+ iQuestion.getQuestionno() + "_" + (pageno + 1) + ".jpg";
        File f = new File(filename);
        if (f.exists())
            f.delete();
    }

    private void prev_page() {
        pageno--;
        setPageState();
    }
    
    private void setPageState() {
        btnPrevPage.setVisibility(View.VISIBLE);
        btnNextPage.setVisibility(View.VISIBLE);
        if (piccount == 1) {
            btnPrevPage.setVisibility(View.GONE);
            btnNextPage.setVisibility(View.GONE);
        } else {
            if (pageno == 0) {
                btnPrevPage.setVisibility(View.GONE);
            } else if (pageno == piccount - 1) {
                btnNextPage.setVisibility(View.GONE);
            }
        }
        mBarCenterTitleTv.setText("第" + (pageno + 1) + "页,共" + piccount + "页");
        startTask(TASK_GET_IMGPIC);
    }

    private void next_page() {
        pageno ++;
        setPageState();;
    }

    private void pen() {
        popTools.dismiss();
        setpenstyle(STATUS_PEN);
    }

    private void eraser() {
        popTools.dismiss();
        setpenstyle(STATUS_ERASER);
    }

    private void rect() {
        popTools.dismiss();
        setpenstyle(STATUS_RECT);
    }

    private void line() {
        popTools.dismiss();
        setpenstyle(STATUS_LINE);
    }

    private void arrow() {
        popTools.dismiss();
        setpenstyle(STATUS_ARROW);
    }

    private void circle() {
        popTools.dismiss();
        setpenstyle(STATUS_CIRCLE);
    }

    private void oval() {
        popTools.dismiss();
        setpenstyle(STATUS_OVAL);
    }

    private void blue() {
        popTools.dismiss();
        setpencolor(Color.BLUE);
    }

    private void black() {
        popTools.dismiss();
        setpencolor(Color.BLACK);
    }

    private void purple() {
        popTools.dismiss();
        setpencolor(c_purple);
    }

    private void setpencolor(int cc) {
        Drawable currentDraw = getResources().getDrawable(R.drawable.correcting_selected);
        pencolor = cc;
        if (cc == Color.RED) {
            b_black.setImageDrawable(currentDraw);
            b_purple.setImageDrawable(null);
            b_blue.setImageDrawable(null);
        } else if (cc == c_purple) {
            b_black.setImageDrawable(null);
            b_purple.setImageDrawable(currentDraw);
            b_blue.setImageDrawable(null);
        } else if (cc == Color.BLUE) {
            b_black.setImageDrawable(null);
            b_purple.setImageDrawable(null);
            b_blue.setImageDrawable(currentDraw);
        }
    }

    /** 设置画笔的状态 */
    private void setpenstyle(int pp) {
        penstyle = pp;
        Drawable currentDraw = getResources().getDrawable(R.drawable.correcting_selected);
        b_pen.setImageDrawable(null);
        b_line.setImageDrawable(null);
        b_arrow.setImageDrawable(null);
        b_oval.setImageDrawable(null);
        b_circle.setImageDrawable(null);
        b_rect.setImageDrawable(null);
        b_eraser.setImageDrawable(null);

        switch (pp) {
        case STATUS_PEN:
            b_pen.setImageDrawable(currentDraw);
            break;
        case STATUS_LINE:
            b_line.setImageDrawable(currentDraw);
            break;
        case STATUS_ARROW:
            b_arrow.setImageDrawable(currentDraw);
            break;
        case STATUS_OVAL:
            b_oval.setImageDrawable(currentDraw);
            break;
        case STATUS_CIRCLE:
            b_circle.setImageDrawable(currentDraw);
            break;
        case STATUS_RECT:
            b_rect.setImageDrawable(currentDraw);
            break;
        case STATUS_ERASER:
            b_eraser.setImageDrawable(currentDraw);
            break;
        }
    }

    private void savejpg() {
        String filename = appdir + "/" + Constant.USER_IASKUNAME + "/" + eid + "/" + iQuestion.getQuestionno()+"/"+iQuestion.getSubmitTimes()+"/" + "/"
                + iQuestion.getQuestionno() + "_" + (pageno + 1) + ".jpg";
        File ff = new File(appdir + "/" + Constant.USER_IASKUNAME + "/" + eid + "/" + iQuestion.getQuestionno()+"/"+iQuestion.getSubmitTimes());
        if (!ff.exists()) {
            try {
                // 按照指定的路径创建文件夹
                ff.mkdirs();
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
        File f = new File(filename);
        FileOutputStream fOut = null;
        try {
            if (!f.exists())
                f.createNewFile();
            fOut = new FileOutputStream(f);
        } catch (IOException e) {
        }
        picimg[pageno].compress(Bitmap.CompressFormat.JPEG, 100, fOut);
        try {
            fOut.flush();
            fOut.close();
        } catch (IOException e) {
        }
    }

    private void drawArrow(Canvas g, Paint p, float x1, float y1, float x2, float y2) {
        float pw = (float) g_penWidth;
        double arrowlen = 10 * pw;
        double arc = 10 * Math.PI / 180;
        double x3, y3, x4, y4, x5, y5, len;
        len = Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
        if (x2 == x1) {
            if (y2 > y1 + arrowlen) {
                y5 = y2 - ((pw - 1) / 2) / Math.tan(arc);
                x5 = x2;

                y3 = y2 - arrowlen * Math.cos(arc);
                y4 = y3;
                x3 = x2 - arrowlen * Math.sin(arc);
                x4 = x2 + arrowlen * Math.sin(arc);

            } else if (y2 + arrowlen < y1) {
                y3 = y2 + arrowlen * Math.cos(arc);
                y4 = y3;
                x3 = x2 - arrowlen * Math.sin(arc);
                x4 = x2 + arrowlen * Math.sin(arc);
                y5 = y2 + ((pw - 1) / 2) / Math.tan(arc);
                x5 = x2;

            } else {
                y3 = y2;
                y4 = y1;
                x3 = x2;
                x4 = x1;
                y5 = y2;
                x5 = x2;
            }
        } else if (x2 > x1) {
            if (y2 > y1) {
                y3 = y2 - arrowlen * Math.cos(Math.asin((x2 - x1) / len) - arc);
                y4 = y2 - arrowlen * Math.cos(Math.asin((x2 - x1) / len) + arc);
                x3 = x2 - arrowlen * Math.sin(Math.asin((x2 - x1) / len) - arc);
                x4 = x2 - arrowlen * Math.sin(Math.asin((x2 - x1) / len) + arc);

            } else if (y2 < y1) {
                y3 = y2 + arrowlen * Math.cos(Math.asin((x2 - x1) / len) - arc);
                y4 = y2 + arrowlen * Math.cos(Math.asin((x2 - x1) / len) + arc);
                x3 = x2 - arrowlen * Math.sin(Math.asin((x2 - x1) / len) - arc);
                x4 = x2 - arrowlen * Math.sin(Math.asin((x2 - x1) / len) + arc);

            } else {
                x3 = x2 - arrowlen * Math.cos(arc);
                x4 = x3;
                y3 = y2 - arrowlen * Math.sin(arc);
                y4 = y2 + arrowlen * Math.sin(arc);
            }
            x5 = x2 - (((pw - 1) / 2) / Math.tan(arc)) * (x2 - x1) / len;
            y5 = y2 - (((pw - 1) / 2) / Math.tan(arc)) * (y2 - y1) / len;

        } else {
            if (y2 > y1) {
                y3 = y2 - arrowlen * Math.cos(Math.asin((x1 - x2) / len) - arc);
                y4 = y2 - arrowlen * Math.cos(Math.asin((x1 - x2) / len) + arc);
                x3 = x2 + arrowlen * Math.sin(Math.asin((x1 - x2) / len) - arc);
                x4 = x2 + arrowlen * Math.sin(Math.asin((x1 - x2) / len) + arc);

            } else if (y2 < y1) {
                y3 = y2 + arrowlen * Math.cos(Math.asin((x1 - x2) / len) - arc);
                y4 = y2 + arrowlen * Math.cos(Math.asin((x1 - x2) / len) + arc);
                x3 = x2 + arrowlen * Math.sin(Math.asin((x1 - x2) / len) - arc);
                x4 = x2 + arrowlen * Math.sin(Math.asin((x1 - x2) / len) + arc);

            } else {
                x3 = x2 + arrowlen * Math.cos(arc);
                x4 = x3;
                y3 = y2 - arrowlen * Math.sin(arc);
                y4 = y2 + arrowlen * Math.sin(arc);
            }
            x5 = x2 - (((pw - 1) / 2) / Math.tan(arc)) * (x2 - x1) / len;
            y5 = y2 - (((pw - 1) / 2) / Math.tan(arc)) * (y2 - y1) / len;

        }
        p.setStyle(Paint.Style.FILL);
        Path path = new Path();

        path.moveTo(x2, y2);
        path.lineTo((float) x3, (float) y3);
        path.lineTo((float) x4, (float) y4);
        path.close();

        g.drawPath(path, p);
        p.setStyle(Paint.Style.STROKE);
        g.drawLine(x1, y1, (float) x5, (float) y5, p);
    }
    
    private void getImageOk() {
        mProgressDialog.dismiss();
        Bitmap bmp = Bitmap.createScaledBitmap(mCurBitmap, imgv.getWidth(), imgv.getHeight(), false);
        picimg[pageno] = Bitmap.createScaledBitmap(bmp, imgv.getWidth(), imgv.getHeight(), false).copy(
                Config.ARGB_8888, true);
        bgnimg[pageno] = Bitmap.createScaledBitmap(bmp, imgv.getWidth(), imgv.getHeight(), false).copy(
                Config.ARGB_8888, true);
        pic_w = picimg[pageno].getWidth();
        pic_h = picimg[pageno].getHeight();
        pic_w_scale_read = pic_w / 800f;
        pic_h_scale_read = pic_h / 600f;
        if (mCommandArr[pageno] != null && !"".equals(mCommandArr[pageno]) && !"null".equals(mCommandArr[pageno])) {
            String[] arr = mCommandArr[pageno].split("#");
            for (int i = 0; i < arr.length; i++) {
                exeCommand(arr[i]);
            }
        }
        getLocalJpg();
        pencolor = Color.BLACK;
        imgv.setImageBitmap(picimg[pageno]);
    }

    @Override
    public int startTask(int taskId) {
        if (taskId == TASK_SUBMIT_HANDIMG) {
            mProgressDialog.setMessage("正在提交...");
            mProgressDialog.show();
        }else if (taskId == TASK_GET_IMGPIC) {
            mProgressDialog.setMessage("正在加载...");
            mProgressDialog.show();
        }
        return super.startTask(taskId);
    }

    @Override
    public Status onTaskInBackground(int taskId, Bundle bundle) {
        switch (taskId) {
        case TASK_SUBMIT_HANDIMG: {
            IDataManager manager = DataManager.getInstance();
            ReturnData<String> mReturnData = manager.submitErrorUserAnswer(Constant.USER_IASKUNAME, eid,
                    iQuestion.getQuestionno(), iQuestion.getUseranswer(), iQuestion.getIsattach(),
                    iQuestion.getQuestion_score(), iQuestion.getQuestion_type_id(), subjectid, 0,
                    iQuestion.getSubmitTimes());
            String mAnswerid = mReturnData.getData();
            for (int i = 0; i < piccount; i++) {
                Bitmap temp = Bitmap.createBitmap(picimg[i]).copy(Config.ARGB_8888, false);
                manager.uploadJpg(Constant.USER_IASKUNAME, eid, mAnswerid, String.valueOf(i + 1),
                        Base64.encode(bitmap2Bytes(temp)));
                temp.recycle();
            }
            return new Status(mReturnData);
        }
        case TASK_START_SYSTEMRECOMMEND:{
            IDataManager manager = DataManager.getInstance();
            manager.startSystemRecommand(eid, iQuestion.getQuestionno(),
                    iQuestion.getQuestion_score(), iQuestion.getQuestion_type_id());
        }
        break;
        case TASK_GET_IMGPIC:{
            String loadPath = Constant.SERVERURL + Constant.DATA_UPLOAD + mAnswerid + "_" + (pageno + 1) + ".jpg";
            IDataManager manager = DataManager.getInstance();
            ReturnData<Bitmap> mReturnData = manager.loadSubmitImage(this, loadPath, mAnswerid);
            mCurBitmap = mReturnData.getData();
            return new Status(mReturnData);
        }
        }
        return super.onTaskInBackground(taskId, bundle);
    }

    public int onTaskComplete(int taskId, Status status) {
        switch (taskId) {
        case TASK_SUBMIT_HANDIMG: {
            mProgressDialog.dismiss();
            BaseUtil.showText(this, "上传成功");
            startTask(TASK_START_SYSTEMRECOMMEND);
        }
            break;
        case TASK_GET_IMGPIC:{
            getImageOk();
        }
        }
        return super.onTaskComplete(taskId, status);
    }

    private byte[] bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        return baos.toByteArray();
    }
    
    private void setPen(String ss) {
        String[] spen = ss.split(":");
        g_penWidth = Integer.parseInt(spen[1]);
        // Toast.makeText(ClassShow.this, ss,Toast.LENGTH_SHORT).show();
        pencolor = Integer.parseInt(spen[2]);
        switch (Integer.parseInt(spen[2])) {
        case 1:
            pencolor = Color.RED;
            break;
        case 2:
            pencolor = Color.BLUE;
            break;
        case 3:
            pencolor = c_purple;
            break;
        case 4:
            pencolor = Color.BLACK;
            break;
        case 5:
            pencolor = Color.YELLOW;
            break;
        default:
            pencolor = Color.RED;// android端传递的颜色int值
            break;
        }

        switch (Integer.parseInt(spen[3])) {
        case 1:
            g_penDash = 0;
            break;
        case 2:
            g_penDash = 1;
            break;
        case 3:
            g_penDash = 2;
            break;
        case 4:
            g_penDash = 3;
            // g_penDash = DashStyle.DashDotDot ;
            break;
        }
    }

    private void exeCommand(String displaytxt) {
        Canvas cv = null;

        Paint p = new Paint();
        p.setColor(pencolor);
        p.setStyle(Paint.Style.STROKE);
        p.setStrokeWidth(g_penWidth);
        p.setAntiAlias(true);

        float x1, y1, x2, y2;

        if (displaytxt.startsWith("SetPen")) {
            setPen(displaytxt.substring(6, displaytxt.indexOf(";")));
            p.setColor(pencolor);
            p.setStrokeWidth(g_penWidth);
            if (g_penDash == 0)
                p.setPathEffect(null);
            else if (g_penDash == 1)
                p.setPathEffect(new DashPathEffect(new float[] { 8, 2, 8, 2 }, 1));
            else if (g_penDash == 2)
                p.setPathEffect(new DashPathEffect(new float[] { 12, 2, 3, 2 }, 1));
            displaytxt = displaytxt.substring(displaytxt.indexOf(";") + 1);

        }
        if (displaytxt.startsWith("Pen:")) {
            p.setPathEffect(null);
            String[] pen = displaytxt.split(":");
            points.clear();
            for (int i = 0; i < pen.length / 2; i++) {
                Point a = new Point(Float.parseFloat(pen[i * 2 + 1]) * pic_w_scale_read,
                        Float.parseFloat(pen[i * 2 + 2]) * pic_h_scale_read);
                points.add(a);
            }
            cv = new Canvas(picimg[pageno]);
            for (int i = 0; i < points.size() - 1; i++) {
                Point pp = points.get(i);
                Point pp1 = points.get(i + 1);
                cv.drawLine(pp.getX(), pp.getY(), pp1.getX(), pp1.getY(), p);
            }
            cv.save(Canvas.ALL_SAVE_FLAG);// 保存

            points.clear();

        } else if (displaytxt.startsWith("Erase:")) {
            String[] pen = displaytxt.split(":");
            rects.clear();
            for (int i = 0; i < pen.length / 4; i++) {
                Rectangle a = new Rectangle();
                a.setX((int) (Float.parseFloat(pen[i * 4 + 1]) * pic_w_scale_read));
                a.setY((int) (Float.parseFloat(pen[i * 4 + 2]) * pic_h_scale_read));
                a.setWidth((int) (Float.parseFloat(pen[i * 4 + 3])));
                a.setHeight((int) (Float.parseFloat(pen[i * 4 + 4])));
                rects.add(a);
            }
            cv = new Canvas(picimg[pageno]);

            Bitmap sclone = null;
            for (int i = 0; i < rects.size(); i++) {
                Rectangle rc = rects.get(i);
                if (bgnimg[pageno] != null) {
                    sclone = Bitmap.createBitmap(bgnimg[pageno], rc.getX(), rc.getY(), rc.getWidth(), rc.getHeight());
                    cv.drawBitmap(sclone, rc.getX(), rc.getY(), p);
                }
            }
            cv.save(Canvas.ALL_SAVE_FLAG);
            rects.clear();
            if (sclone != null)
                sclone.recycle();

        } else if (displaytxt.startsWith("ClearScreen")) {

            picimg[pageno] = Bitmap.createBitmap(bgnimg[pageno]);
        } else if (displaytxt.startsWith("Line:")) {
            String[] pen = displaytxt.split(":");

            x1 = Integer.parseInt(pen[1]) * pic_w_scale_read;
            y1 = Integer.parseInt(pen[2]) * pic_h_scale_read;
            x2 = Integer.parseInt(pen[3]) * pic_w_scale_read;
            y2 = Integer.parseInt(pen[4]) * pic_h_scale_read;

            cv = new Canvas(picimg[pageno]);
            cv.drawLine(x1, y1, x2, y2, p);
            cv.save(Canvas.ALL_SAVE_FLAG);

        } else if (displaytxt.startsWith("Rectangle:")) {
            String[] pen = displaytxt.split(":");
            x1 = Float.parseFloat(pen[1]) * pic_w_scale_read;
            y1 = Float.parseFloat(pen[2]) * pic_h_scale_read;
            x2 = Float.parseFloat(pen[3]) * pic_w_scale_read;
            y2 = Float.parseFloat(pen[4]) * pic_h_scale_read;
            Rect rc1 = new Rect();
            rc1.left = (int) x1;
            rc1.right = (int) x2;
            rc1.top = (int) y1;
            rc1.bottom = (int) y2;
            cv = new Canvas(picimg[pageno]);
            cv.drawRect(rc1, p);
            cv.save(Canvas.ALL_SAVE_FLAG);
        } else if (displaytxt.startsWith("Ellipse:")) {
            String[] pen = displaytxt.split(":");
            x1 = Integer.parseInt(pen[1]) * pic_w_scale_read;
            y1 = Integer.parseInt(pen[2]) * pic_h_scale_read;
            x2 = Integer.parseInt(pen[3]) * pic_w_scale_read;
            y2 = Integer.parseInt(pen[4]) * pic_h_scale_read;
            RectF rc1 = new RectF();
            rc1.left = x1;
            rc1.right = x2;
            rc1.top = y1;
            rc1.bottom = y2;
            cv = new Canvas(picimg[pageno]);
            cv.drawOval(rc1, p);
            cv.save(Canvas.ALL_SAVE_FLAG);
        } else if (displaytxt.startsWith("Circle:")) {
            String[] pen = displaytxt.split(":");
            x1 = Integer.parseInt(pen[1]) * pic_w_scale_read;
            y1 = Integer.parseInt(pen[2]) * pic_h_scale_read;
            x2 = Integer.parseInt(pen[3]) * pic_w_scale_read;
            y2 = Integer.parseInt(pen[4]) * pic_h_scale_read;
            float radius = (float) (Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)));
            cv = new Canvas(picimg[pageno]);
            cv.drawCircle(x1, y1, radius, p);
            cv.drawCircle(x1, y1, 1, p);
            cv.save(Canvas.ALL_SAVE_FLAG);
        } else if (displaytxt.startsWith("Arrow:")) {
            String[] pen = displaytxt.split(":");
            x1 = Integer.parseInt(pen[1]) * pic_w_scale_read;
            y1 = Integer.parseInt(pen[2]) * pic_h_scale_read;
            x2 = Integer.parseInt(pen[3]) * pic_w_scale_read;
            y2 = Integer.parseInt(pen[4]) * pic_h_scale_read;
            cv = new Canvas(picimg[pageno]);
            drawArrow(cv, p, x1, y1, x2, y2);
            cv.save(Canvas.ALL_SAVE_FLAG);
        } else if (displaytxt.startsWith("Ten:")) {
            String[] pen = displaytxt.split(":");
            x1 = Integer.parseInt(pen[1]) * pic_w_scale_read;
            y1 = Integer.parseInt(pen[2]) * pic_h_scale_read;
            x2 = Integer.parseInt(pen[3]) * pic_w_scale_read;
            y2 = Integer.parseInt(pen[4]) * pic_h_scale_read;
            cv = new Canvas(picimg[pageno]);
            drawTen(cv, p, x1, y1, x2, y2);
            cv.save(Canvas.ALL_SAVE_FLAG);
        }
        bgnimg0 = Bitmap.createBitmap(picimg[pageno]);
    }
    
    private void drawTen(Canvas g, Paint p, float x1, float y1, float x2, float y2) {
        drawArrow(g, p, x1 - (x2 - x1) / 6, y1, x2, y1);
        drawArrow(g, p, x1, y1 - (y2 - y1) / 6, x1, y2);
    }


}
